package ldh.im.fxgui.controller.sub;

import com.jfoenix.controls.JFXDialog;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import ldh.im.dto.enums.MessageType;
import ldh.im.fxbase.dao.ImMessageDao;
import ldh.im.fxbase.data.pojo.ImMessage;
import ldh.im.fxbase.service.CollectService;
import ldh.im.fxbase.util.*;
import ldh.im.fxgui.component.message.MessageListViewHandler;
import ldh.im.fxgui.handle.CollectHandler;
import ldh.im.fxgui.util.UiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消息被选择组件
 */
public class MessageSelectController implements Initializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageSelectController.class);

    @FXML private Pane selectPane;

    private MessageListViewHandler messageListViewHandler;

    public void setMessageListViewHandler(MessageListViewHandler messageListViewHandler) {
        this.messageListViewHandler = messageListViewHandler;
    }

    public void show() {
        selectPane.setVisible(true);
    }

    public void hide() {
        selectPane.setVisible(false);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    @FXML
    private void close() {
        messageListViewHandler.messageSelectProperty().set(false);
    }

    @FXML
    private void transferOneToOneMessages() {
        showTransferMessageDialog(true);
        close();
    }

    @FXML
    private void transferMessages() {
        showTransferMessageDialog(false);
        close();
    }

    @FXML
    private void collectMessage() {
        List<ImMessage> messages = messageListViewHandler.getSelectedMessages();
        if (messages.size() < 1) return;

        StackPane dialogRoot = messageListViewHandler.getDialogRoot();

        CollectHandler collectHandler = BeanFactory.getInstance().getBean(CollectHandler.class);
        Task task = collectHandler.collectMessages(dialogRoot, messages);
        task.setOnSucceeded(s->{
            DialogUtil.showSuccess(dialogRoot, "收藏成功");
        });
        close();
    }

    @FXML
    private void saveMessages() {
        List<ImMessage> messages = messageListViewHandler.getSelectedMessages();
        if (messages.size() < 1) return;

        StackPane dialogRoot = messageListViewHandler.getDialogRoot();

        List<ImMessage> canSaveMessage = messages.stream()
                .filter(m->m.getMessageType() == MessageType.File || m.getMessageType() == MessageType.Video ||
                        m.getMessageType() == MessageType.Image).collect(Collectors.toList());
        if (canSaveMessage.size() < 1) {
            DialogUtil.alert("提醒", "只有图片、文件、视频才能保存到本地");
            return;
        }
        DirectoryChooser directoryChooser = new DirectoryChooser();
        File file = directoryChooser.showDialog(dialogRoot.getScene().getWindow());
        if (file == null) return;

        Task copyTask = new Task() {

            @Override
            protected Object call() throws Exception {
                for (ImMessage imMessage : canSaveMessage) {
                    String filePath = FileUtil.getFilePath(imMessage);
                    String fileName = imMessage.initMessageExt().getOriginalName();
                    File toFile = new File(file, fileName);
                    Files.copy(Paths.get(filePath), toFile.toPath());
                }
                return null;
            }
        };
        ThreadPoolUtil.submitTask(copyTask, "保存文件");
        copyTask.setOnSucceeded(s->{
            DialogUtil.showSuccess(dialogRoot, "保存成功");
        });
    }

    @FXML
    private void deleteMessages() {
        List<ImMessage> messages = messageListViewHandler.getSelectedMessages();
        if (messages.size() < 1) return;

        Task task = new Task() {

            @Override
            protected Object call() throws Exception {
                ImMessageDao imMessageDao = BeanFactory.getInstance().getBean(ImMessageDao.class);
                imMessageDao.batchDeleteMessages(messages);
                return null;
            }
        };
        ThreadPoolUtil.submitTask(task);
        task.setOnSucceeded(s->{
            messageListViewHandler.deleteMessages(messages);
        });

    }

    private void showTransferMessageDialog(boolean isOneToOneTransfer) {
        List<ImMessage> messages = messageListViewHandler.getSelectedMessages();
        if (messages.size() < 1) return;

        RegionUtil.FxmlBean<Pane, TransferMessageController> fxmlBean = RegionUtil.loadFxmlBean(this.getClass().getResource("/fxml/sub/TransferMessagePane.fxml"));
        StackPane dialogRoot = messageListViewHandler.getDialogRoot();
        JFXDialog dialog = null;
        if (dialogRoot != null) {
            dialog = DialogUtil.show(dialogRoot, fxmlBean.getNode(), false);
        } else {
            dialog = DialogUtil.show(fxmlBean.getNode(), false);
        }

        fxmlBean.getController().setDialog(dialog);
        fxmlBean.getController().setTransferImages(messages, isOneToOneTransfer);
    }
}
